<template>
  <div class="box key-indicators" :class="{ 'production-mode': isProductionMode }">
    <div class="tit" data-icon="indicator">
      <div class="tit-content">
        <span class="tit-main">关键指标</span>
        <transition name="group-name-fade" mode="out-in">
          <span :key="currentGroupIndex" class="group-name">{{ currentGroupName }}</span>
        </transition>
      </div>
      <div class="bottom-line"></div>
    </div>
    
    <div class="boxnav indicators-container-wrapper" @mouseenter="isPaused = true" @mouseleave="isPaused = false">
      <div class="indicators-scroll-container" id="indicatorsContainer">
        <!-- 加载状态由全局进度条显示，这里不再显示本地进度 -->
        <div v-if="isLoading && allIndicators.length === 0" class="loading-indicator" style="text-align: center; padding: 50px; color: rgba(255,255,255,0.6);">
          <div>正在加载指标数据...</div>
        </div>
        
        <!-- 错误状态 -->
        <div v-else-if="error" class="error-indicator" style="text-align: center; padding: 30px; color: #ff6b6b;">
          <div>{{ error }}</div>
          <div style="font-size: 12px; margin-top: 10px; opacity: 0.8;">请检查网络连接或数据源</div>
          <div v-if="debugInfo" style="margin-top: 15px; font-size: 10px; color: #ccc; text-align: left;">
            <div>调试信息:</div>
            <pre>{{ debugInfo }}</pre>
          </div>
        </div>
        
        <!-- 指标卡片 -->
        <div v-else class="indicators-container">
          <transition name="group-fade" mode="out-in">
            <div 
              :key="currentGroupIndex"
              class="indicators-grid"
            >
              <div 
                v-for="(indicator, index) in displayIndicators" 
                :key="indicator.name"
                class="indicator-card"
                :class="indicator.cardClass"
                :style="indicator.accentStyle"
              >
                <span class="indicator-accent" :style="indicator.accentBarStyle"></span>
                <div class="indicator-content-new">
                  <!-- 顶部：左侧标题，右侧数值 -->
                  <div class="indicator-top-row">
                    <div class="indicator-label">{{ indicator.name }}</div>
                    <div class="indicator-value-right">
                      <span class="value-number-new">{{ indicator.value }}</span>
                      <span class="value-unit-new">{{ indicator.unit }}</span>
                    </div>
                  </div>

                  <!-- 底部：右侧同比胶囊 + 迷你趋势图 -->
                  <div class="indicator-bottom-row">
                    <span 
                      v-if="indicator.changeValue" 
                      class="value-change-new" 
                      :class="indicator.changeClass"
                    >
                      <span class="change-type">同比</span>
                      {{ indicator.changeDirection }}{{ Math.abs(indicator.changeValue) }}%
                    </span>

                    <div class="indicator-chart">
                      <MiniTrendChart 
                        v-if="indicator.trendData && indicator.trendData.length > 0"
                        :data="indicator.trendData"
                        :width="120"
                        :height="30"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </transition>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useIndicatorAPI } from '../composables/useIndicatorAPI.js'
import MiniTrendChart from './MiniTrendChart.vue'
import { getCurrentConfig } from '../config/environment.js'

const { isLoading, loadingProgress, error, loadKeyIndicators } = useIndicatorAPI()

// 检测是否为生产环境或受限容器环境
const isProductionMode = ref(false)

// 检测父容器是否有高度限制
const detectContainerRestriction = () => {
  if (typeof window !== 'undefined') {
    // 方式1: 检测环境
    const config = getCurrentConfig()
    const isProd = config === getCurrentConfig() && 
                   (window.location.hostname.includes('prod') || 
                    !window.location.hostname.includes('localhost'))
    
    // 方式2: 检测父容器样式 (在挂载后检测)
    return isProd
  }
  return false
}

// 五组指标配置 - 必须先定义，因为下面的变量会用到
const indicatorGroups = [
  {
    groupName: '核心指标',
    indicators: ['资本充足率', '核心一级资本充足率', '一级资本充足率']
  },
  {
    groupName: '盈利能力',
    indicators: ['净息差', '资本利润率', '资产利润率']
  },
  {
    groupName: '资产质量',
    indicators: ['不良贷款率', '拨备覆盖率', '关注类贷款占比']
  },
  {
    groupName: '运营效率',
    indicators: ['成本收入比', '存贷比','净利润']
  },
  {
    groupName: '流动性风险',
    indicators: ['流动性覆盖率(LCR)', '净稳定资金比例', '流动性缺口率']
  }
]

// 指标数据
const indicators = ref([])
const debugInfo = ref('')

// 全量指标缓存（一次性加载全部，切换时不再请求）
const allIndicators = ref([])

// 轮播相关状态
const currentGroupIndex = ref(0)
const currentGroupName = ref(indicatorGroups[0].groupName)
const isTransitioning = ref(false)
const isPaused = ref(false) // 悬停暂停
let carouselTimer = null

// 处理指标数据 - 处理最近一年的趋势数据
const processIndicatorData = (results) => {
  const processedIndicators = []
  
  // console.debug('处理指标数据，收到结果条目:', results?.length)
  
  results.forEach(result => {
    // 获取指标名称（兼容字符串和对象格式）
    const indicatorName = typeof result.indicator === 'object' ? result.indicator.name : result.indicator
    
    // console.debug(`处理指标 ${indicatorName}`)
    if (result.success && result.data && result.data.datas && result.data.datas.length > 0) {
      const records = result.data.datas
      const latestRecord = records[0]
      
      // 提取最新数据
      const bussDate = latestRecord[0]
      let indexValue = parseFloat(latestRecord[3])
      const orgNo = latestRecord[2]
      
      // 百分比指标需要乘以100%展示
      if (indicatorName && (indicatorName.includes('资本充足率') || 
          indicatorName.includes('不良贷款率') || 
          indicatorName.includes('拨备覆盖率') ||
          indicatorName.includes('净息差') ||
          indicatorName.includes('资本利润率') ||
          indicatorName.includes('资产利润率') ||
          indicatorName.includes('关注类贷款占比') ||
          indicatorName.includes('成本收入比') ||
          indicatorName.includes('存贷比') ||
          indicatorName.includes('流动性覆盖率') ||
          indicatorName.includes('净稳定资金比例') ||
          indicatorName.includes('流动性缺口率'))) {
        indexValue = indexValue * 100
      }
      
      // 计算变化值（与上期相比）
      let changeValue = 0
      let changeDirection = ''
      if (records.length > 1) {
        let previousValue = parseFloat(records[1][3])
        // 百分比指标需要乘以100%展示
        if (indicatorName && (indicatorName.includes('资本充足率') || 
            indicatorName.includes('不良贷款率') || 
            indicatorName.includes('拨备覆盖率') ||
            indicatorName.includes('净息差') ||
            indicatorName.includes('资本利润率') ||
            indicatorName.includes('资产利润率') ||
            indicatorName.includes('关注类贷款占比') ||
            indicatorName.includes('成本收入比') ||
            indicatorName.includes('存贷比') ||
            indicatorName.includes('流动性覆盖率') ||
            indicatorName.includes('净稳定资金比例') ||
            indicatorName.includes('流动性缺口率'))) {
          previousValue = previousValue * 100
        }
        changeValue = ((indexValue - previousValue) / previousValue * 100).toFixed(2)
        changeDirection = changeValue > 0 ? '↑' : changeValue < 0 ? '↓' : '='
        changeValue = Math.abs(changeValue)
      }
      
      // 提取趋势数据（最多12个月）
      const trendData = records.map(record => {
        let value = parseFloat(record[3])
        // 百分比指标需要乘以100%展示
        if (indicatorName && (indicatorName.includes('资本充足率') || 
            indicatorName.includes('不良贷款率') || 
            indicatorName.includes('拨备覆盖率') ||
            indicatorName.includes('净息差') ||
            indicatorName.includes('资本利润率') ||
            indicatorName.includes('资产利润率') ||
            indicatorName.includes('关注类贷款占比') ||
            indicatorName.includes('成本收入比') ||
            indicatorName.includes('存贷比') ||
            indicatorName.includes('流动性覆盖率') ||
            indicatorName.includes('净稳定资金比例') ||
            indicatorName.includes('流动性缺口率'))) {
          value = value * 100
        }
        return {
          date: record[0],
          value: value
        }
      }).reverse() // 反转数组，让时间从早到晚排序
      
      // 创建指标对象
      const indicator = createIndicator(indicatorName, indexValue, changeValue, changeDirection, bussDate, orgNo, trendData)
      processedIndicators.push(indicator)
    } else if (!result.success) {
      console.warn(`指标 ${indicatorName} 获取失败:`, result.error)
    }
  })
  
  // 返回全部成功处理的指标
  // console.debug('已处理的全部指标条目:', processedIndicators.length)
  return processedIndicators
}

// 创建指标对象
const createIndicator = (name, value, changeValue, changeDirection, date, orgNo, trendData = []) => {
  let cardClass = 'default-indicator'
  let status = ''
  let statusClass = ''
  let unit = '%' // 大部分指标都是百分比
  let safeThreshold = 0
  let accentStyle = {}
  let accentBarStyle = {}
  
  // 根据指标类型设置样式和阈值
  if (name.includes('资本充足率')) {
    cardClass = 'capital-indicator'
    accentStyle = { borderLeft: '0' }
    accentBarStyle = { background: '#29d9d5', boxShadow: '0 0 8px #29d9d5' }
    if (name === '核心一级资本充足率') {
      safeThreshold = 7.5
    } else if (name === '一级资本充足率') {
      safeThreshold = 9.5
    } else {
      safeThreshold = 10.5
    }
    status = value >= safeThreshold ? '安全' : '预警'
    statusClass = value >= safeThreshold ? 'status-safe' : 'status-warning'
  } else if (name.includes('不良贷款率')) {
    cardClass = 'risk-indicator'
    accentStyle = { borderLeft: '0' }
    accentBarStyle = { background: '#ff6b6b', boxShadow: '0 0 8px #ff6b6b' }
    safeThreshold = 2.0
    status = value <= safeThreshold ? '正常' : '预警'
    statusClass = value <= safeThreshold ? 'status-safe' : 'status-warning'
  } else if (name.includes('拨备覆盖率')) {
    cardClass = 'provision-indicator'
    accentStyle = { borderLeft: '0' }
    accentBarStyle = { background: '#00d4aa', boxShadow: '0 0 8px #00d4aa' }
    safeThreshold = 150
    status = value >= safeThreshold ? '充足' : '不足'
    statusClass = value >= safeThreshold ? 'status-safe' : 'status-warning'
  } else if (name.includes('净息差') || name.includes('资本利润率')) {
    cardClass = 'profit-indicator'
    accentStyle = { borderLeft: '0' }
    accentBarStyle = { background: '#ffc107', boxShadow: '0 0 8px #ffc107' }
    safeThreshold = name.includes('净息差') ? 2.0 : 10.0
    status = value >= safeThreshold ? '优秀' : '一般'
    statusClass = value >= safeThreshold ? 'status-safe' : 'status-warning'
  } else if (name.includes('成本收入比')) {
    cardClass = 'efficiency-indicator'
    accentStyle = { borderLeft: '0' }
    accentBarStyle = { background: '#9c27b0', boxShadow: '0 0 8px #9c27b0' }
    safeThreshold = 40
    status = value <= safeThreshold ? '高效' : '一般'
    statusClass = value <= safeThreshold ? 'status-safe' : 'status-warning'
  } else if (name.includes('存贷比')) {
    cardClass = 'efficiency-indicator'
    accentStyle = { borderLeft: '0' }
    accentBarStyle = { background: '#9c27b0', boxShadow: '0 0 8px #9c27b0' }
    safeThreshold = 75
    status = value <= safeThreshold ? '合理' : '偏高'
    statusClass = value <= safeThreshold ? 'status-safe' : 'status-warning'
  } else if (name.includes('净利润')) {
    cardClass = 'efficiency-indicator'
    accentStyle = { borderLeft: '0' }
    accentBarStyle = { background: '#4caf50', boxShadow: '0 0 8px #4caf50' }
    unit = '亿元'
    safeThreshold = 30
    status = value >= safeThreshold ? '优秀' : '一般'
    statusClass = value >= safeThreshold ? 'status-safe' : 'status-warning'
  } else if (name.includes('流动性覆盖率') || name.includes('净稳定资金比例')) {
    cardClass = 'liquidity-indicator'
    accentStyle = { borderLeft: '0' }
    accentBarStyle = { background: '#2196f3', boxShadow: '0 0 8px #2196f3' }
    safeThreshold = 100
    status = value >= safeThreshold ? '充足' : '不足'
    statusClass = value >= safeThreshold ? 'status-safe' : 'status-warning'
  }

  // 针对同一类别中的具体指标，赋予不同的强调色以提升区分度
  if (name === '资本充足率') {
    accentBarStyle = { background: '#29d9d5', boxShadow: '0 0 8px #29d9d5' }
  } else if (name === '核心一级资本充足率') {
    accentBarStyle = { background: '#3C8BFF', boxShadow: '0 0 8px #3C8BFF' }
  } else if (name === '一级资本充足率') {
    accentBarStyle = { background: '#9C27B0', boxShadow: '0 0 8px #9C27B0' }
  } else if (name === '关注类贷款占比') {
    accentBarStyle = { background: '#FFC107', boxShadow: '0 0 8px #FFC107' }
  } else if (name === '流动性覆盖率(LCR)') {
    accentBarStyle = { background: '#00BCD4', boxShadow: '0 0 8px #00BCD4' }
  } else if (name === '净稳定资金比例') {
    accentBarStyle = { background: '#2196F3', boxShadow: '0 0 8px #2196F3' }
  } else if (name === '流动性缺口率') {
    accentBarStyle = { background: '#FF8A65', boxShadow: '0 0 8px #FF8A65' }
  }
  
  return {
    name,
    value: value.toFixed(2),
    unit,
    status,
    statusClass,
    changeValue: changeValue ? parseFloat(changeValue) : 0,
    changeDirection,
    changeClass: changeDirection === '↑' ? 'change-up' : changeDirection === '↓' ? 'change-down' : '',
    date,
    orgNo,
    cardClass,
    accentStyle,
    accentBarStyle,
    trendData
  }
}

// 获取指标样式类
const getIndicatorClass = (name) => {
  if (name.includes('资本充足率')) return 'car-indicator'
  if (name.includes('拨备覆盖率')) return 'provision-indicator'
  if (name.includes('不良贷款率')) return 'npl-indicator'
  if (name.includes('迁徙率')) return 'migration-indicator'
  if (name.includes('存款') || name.includes('存单')) return 'deposit-indicator'
  return 'default-indicator'
}

// 显示的指标（用于计算属性，可以进行过滤或排序）
const displayIndicators = computed(() => {
  const names = indicatorGroups[currentGroupIndex.value].indicators
  const map = new Map(allIndicators.value.map(i => [i.name, i]))
  return names.map(n => map.get(n)).filter(Boolean)
})

// 获取当前组的指标
const getCurrentGroupIndicators = () => {
  return indicatorGroups[currentGroupIndex.value].indicators
}

// 切换到下一组指标
const switchToNextGroup = async () => {
  if (isTransitioning.value) return // 防止重复触发
  
  isTransitioning.value = true
  
  // 切换到下一组
  currentGroupIndex.value = (currentGroupIndex.value + 1) % indicatorGroups.length
  currentGroupName.value = indicatorGroups[currentGroupIndex.value].groupName
  
  // 不再请求接口，直接依赖全量缓存
  // 延迟重置转换状态，确保动画完成（减少延迟时间）
  setTimeout(() => {
    isTransitioning.value = false
  }, 650) // 与优化后的CSS动画时间匹配
}

// 启动自动轮播（每10秒）
const startCarousel = () => {
  if (carouselTimer) clearInterval(carouselTimer)
  carouselTimer = setInterval(() => {
    if (!isPaused.value) {
      switchToNextGroup()
    }
  }, 10000)
}

// 停止轮播（兼容清理）
const stopCarousel = () => {
  if (carouselTimer) {
    clearInterval(carouselTimer)
    carouselTimer = null
  }
}

// 加载当前组的数据
const loadCurrentGroupData = async () => {
  try {
    const currentIndicators = getCurrentGroupIndicators()
    // console.debug('加载当前组指标:', currentIndicators)
    
    // 调用后端，按当前组配置的指标名称批量获取真实数据
    const results = await loadKeyIndicators(currentIndicators)
    indicators.value = processIndicatorData(results)
    
    // console.debug('当前组数据(来自后端)条目:', indicators.value.length)
    
    // 收集调试信息
    const debugData = {
      currentGroup: currentGroupName.value,
      indicators: currentIndicators,
      processedCount: indicators.value.length,
      results: indicators.value.map(i => ({ name: i.name, value: i.value }))
    }
    debugInfo.value = JSON.stringify(debugData, null, 2)
    
  } catch (err) {
    console.error('加载当前组指标失败:', err)
    debugInfo.value = `加载失败: ${err.message}`
  }
}

// 创建模拟数据
const createMockData = (indicatorNames) => {
  const mockValues = {
    '资本充足率': { value: 13.36, change: 1.04, direction: '↑' },
    '核心一级资本充足率': { value: 10.50, change: 0.25, direction: '↓' },
    '净息差': { value: 2.15, change: 0.08, direction: '↑' },
    '资本利润率': { value: 12.5, change: 0.5, direction: '↑' },
    '不良贷款率': { value: 1.85, change: 0.15, direction: '↓' },
    '拨备覆盖率': { value: 165.2, change: 2.3, direction: '↑' },
    '成本收入比': { value: 35.8, change: 1.2, direction: '↓' },
    '存贷比': { value: 68.5, change: 0.8, direction: '↑' },
    '流动性覆盖率': { value: 125.6, change: 3.2, direction: '↑' },
    '净稳定资金比例': { value: 110.8, change: 1.5, direction: '↑' }
  }
  
  // 同时创建所有指标数据，避免异步渲染
  const allIndicators = indicatorNames.map((name, index) => {
    const mock = mockValues[name] || { value: 100, change: 0, direction: '=' }
    
    // 为每个指标创建不同的趋势数据模式
    const trendData = []
    const indicatorSeed = name.charCodeAt(0) + index * 100 // 基于指标名称和索引的种子
    
    for (let i = 11; i >= 0; i--) {
      const date = new Date()
      date.setMonth(date.getMonth() - i)
      const baseValue = mock.value
      
      // 根据不同指标类型创建不同的趋势模式
      let variation = 0
      if (name.includes('资本充足率')) {
        // 资本充足率：相对稳定，小幅波动
        variation = Math.sin((indicatorSeed + i) * 0.3) * 0.5 + Math.cos((indicatorSeed + i) * 0.1) * 0.3
      } else if (name.includes('不良贷款率')) {
        // 不良贷款率：可能有周期性变化
        variation = Math.sin((indicatorSeed + i) * 0.4) * 0.3 + Math.sin((indicatorSeed + i) * 0.8) * 0.2
      } else if (name.includes('拨备覆盖率')) {
        // 拨备覆盖率：可能有较大波动
        variation = Math.cos((indicatorSeed + i) * 0.5) * 2.0 + Math.sin((indicatorSeed + i) * 0.2) * 1.0
      } else if (name.includes('净息差') || name.includes('资本利润率')) {
        // 盈利指标：可能有季节性变化
        variation = Math.sin((indicatorSeed + i) * 0.6) * 0.4 + Math.cos((indicatorSeed + i) * 0.3) * 0.6
      } else if (name.includes('成本收入比') || name.includes('存贷比')) {
        // 效率指标：可能有趋势性变化
        variation = Math.sin((indicatorSeed + i) * 0.7) * 1.2 + (i - 6) * 0.1
      } else if (name.includes('流动性') || name.includes('资金比例')) {
        // 流动性指标：可能波动较大
        variation = Math.sin((indicatorSeed + i) * 0.9) * 1.8 + Math.cos((indicatorSeed + i) * 0.4) * 1.2
      } else {
        // 默认模式
        variation = Math.sin((indicatorSeed + i) * 0.5) * 1.0
      }
      
      const value = Math.max(0, baseValue + variation)
      trendData.push({ date: date.toISOString().slice(0, 10), value })
    }
    
    return {
      name,
      value: mock.value.toFixed(2),
      unit: '%',
      status: '',
      statusClass: '',
      changeValue: mock.change,
      changeDirection: mock.direction,
      changeClass: mock.direction === '↑' ? 'change-up' : mock.direction === '↓' ? 'change-down' : '',
      date: new Date().toISOString().slice(0, 10),
      orgNo: '00000',
      cardClass: 'default-indicator',
      trendData
    }
  })
  
  return allIndicators
}

// 获取数据库中所有资本充足率相关指标
const getAvailableIndicators = async () => {
  try {
    // console.debug('查询数据库中的资本充足率指标...')
    
    // 准备POST数据
    const postData = new URLSearchParams()
    postData.append('action', 'exesql')
    postData.append('jdbcName', 'amsedb')
    postData.append('enc', 'true')
    
    // 查询所有包含"资本充足率"的指标名称
    let sql = `select distinct index_nm from audit_index_total where index_nm like '%资本充足率%' and org_no='00000' order by index_nm`
    sql = encodeURIComponent(sql)
    sql = btoa(sql)
    
    postData.append('sql', sql)
    postData.append('pageIndex', 'undefined')
    postData.append('pageSize', '100')
    postData.append('isSys', 'false')
    postData.append('t', Date.now().toString())
    
    // 发送请求
    const response = await fetch(`http://${window.location.host}/coolv/edatasource/jdbcmgr.do`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        'X-Requested-With': 'XMLHttpRequest',
        'Accept': '*/*'
      },
      body: postData
    })
    
    const data = await response.json()
    // console.debug('查询到的资本充足率指标条目:', Array.isArray(data?.datas) ? data.datas.length : 0)
    
    if (data.datas && data.datas.length > 0) {
      return data.datas.map(row => row[0]).slice(0, 3) // 只取前3个
    }
    
    return []
  } catch (err) {
    console.error('查询可用指标失败:', err)
    return []
  }
}

// 刷新指标数据
const refreshIndicators = async () => {
  try {
    debugInfo.value = ''
    
    // 获取所有指标组中的指标名称
    const allIndicatorNames = indicatorGroups.flatMap(group => group.indicators)
    // console.debug('需要获取的所有指标:', allIndicatorNames)
    
    // 直接使用配置中的指标名称获取数据
    const results = await loadKeyIndicators(allIndicatorNames)
    indicators.value = processIndicatorData(results)
    
    // 收集调试信息
    const debugData = {
      allIndicatorNames,
      processedCount: indicators.value.length,
      indicators: indicators.value.map(i => ({ name: i.name, value: i.value }))
    }
    debugInfo.value = JSON.stringify(debugData, null, 2)
    
  } catch (err) {
    console.error('刷新指标失败:', err)
    debugInfo.value = `刷新失败: ${err.message}`
  }
}

// 组件挂载时加载数据
onMounted(() => {
  // 检测环境模式
  isProductionMode.value = detectContainerRestriction()
  
  // console.debug('KeyIndicators组件已挂载')
  setTimeout(async () => {
    // console.debug('开始加载数据和启动轮播')
    // 一次性加载全部指标数据
    const allNames = indicatorGroups.flatMap(g => g.indicators).map(n => {
      // 拨备覆盖率限定数据来源
      if (n === '拨备覆盖率') {
        return { name: n, where: "ori='信用风险指标补录表'" }
      }
      return n
    })
    const results = await loadKeyIndicators(allNames)
    allIndicators.value = processIndicatorData(results)
    // 启动自动轮播
    startCarousel()
  }, 2000) // 延迟2秒等待页面完全加载
})

// 组件卸载时清理定时器
onUnmounted(() => {
  stopCarousel()
})
</script>

<style scoped>
/* 关键指标 - 布局变量（只需改这里即可全局生效）*/
.key-indicators {
  --ki-card-min-h: 72px; /* 适配新布局，略增高度 */
  isolation: isolate; /* 屏蔽上级元素的融合影响 */
}

/* 生产环境适配模式 - 针对受限容器的样式优化 */
.key-indicators.production-mode {
  /* 确保在受限容器中的样式一致性 */
  box-sizing: border-box !important;
  
  /* 重置可能被外部容器影响的样式 */
  * {
    box-sizing: border-box !important;
  }
}

/* 容器包装器 - 统一开发和生产环境的显示效果 */
.indicators-container-wrapper {
  /* height: 220px; */
  padding: 4px;
  overflow: hidden;
  position: relative;
  width: 100%;
}

/* 确保所有子元素继承正确的字体和颜色 */
.indicators-container-wrapper *,
.indicators-container-wrapper .indicator-card,
.indicators-container-wrapper .indicator-title,
.indicators-container-wrapper .value-number,
.indicators-container-wrapper .indicator-subtitle {
  font-family: Microsoft YaHei, 微软雅黑, PingFang SC, Helvetica Neue, Arial, sans-serif !important;
  color: inherit;
  margin: 0;
  /* padding: 0px; */
}

.indicators-grid {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: repeat(3, auto); /* 让每一行按内容自适应高度，避免重叠 */
  gap: 2px; /* 增大卡片间距，参照资产质量风格 */
  height: 100%;
  width: 100%;
  align-content: start;
  align-items: start;
  perspective: 1000px;
  transform: translateZ(0);
  backface-visibility: hidden;
}

.indicators-grid > .indicator-card {
  animation: none !important;
  transition: none !important;
  opacity: 1 !important;
  position: static;
  grid-column: auto;
  grid-row: auto;
  align-self: start; /* 保持卡片按内容高度 */
}

.indicator-card {
  padding: 12px 12px;
  background: linear-gradient(180deg, rgba(255,255,255,0.06), rgba(255,255,255,0.03));
  border-radius: 10px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  min-height: var(--ki-card-min-h);
  transition: all 0.25s ease;
  overflow: hidden;
  box-sizing: border-box;
  box-shadow: inset 0 0 0 1px rgba(255,255,255,0.04), 0 8px 24px rgba(0,0,0,0.18);
  position: relative;
}

.indicator-card:hover { background: linear-gradient(180deg, rgba(255,255,255,0.08), rgba(255,255,255,0.04)); transform: translateY(-1px); box-shadow: inset 0 0 0 1px rgba(255,255,255,0.06), 0 10px 28px rgba(0,0,0,0.22); }

/* 新的卡片内容布局 - 参照 RiskRadar 样式 */
.indicator-content-new {
  display: flex;
  flex-direction: column;
  /* gap: 8px; */
}

.indicator-top-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  column-gap: 8px;
}

.indicator-bottom-row {
  display: grid;
  grid-template-columns: auto 1fr; /* 左同比，右趋势图 */
  align-items: center;
  gap: 25px;
}

.indicator-chart {
  width: 100%;
  /* min-height: 48px; */
  display: flex;
  align-items: center;
  overflow: hidden;
  /* padding: 6px 8px; */
  border-radius: 8px;
  /* background: rgba(255,255,255,0.06);
  border: 1px solid rgba(255,255,255,0.12); */
}

.indicator-chart svg { width: 100% !important; height: 36px; display: block; }

/* 左侧发光色条 */
.indicator-accent {
  position: absolute;
  top: 10px;
  bottom: 10px;
  width: 3px;
  border-radius: 2px;
  background: #29d9d5;
  box-shadow: 0 0 8px #29d9d5;
}

.indicator-label {
  color: rgba(255, 255, 255, 0.9);
  font-size: 13px;
  font-weight: 500;
  padding-left: 12px; /* 向内缩进，避免贴边 */
  position: relative;
}

/* 左侧小圆点装饰，增强层次感 */
/* 去掉小圆点 */
.indicator-label::before { display: none; content: none; }

.indicator-value-right {
  display: flex;
  align-items: baseline;
}

.value-main {
  display: flex;
  align-items: baseline;
  gap: 1px;
  line-height: 1;
  max-width: 100%;
  overflow: hidden;
  flex-wrap: nowrap;
}

.value-change-row { display: none; }

.value-number-new {
  color: #ffffff;
  font-size: 22px;
  font-weight: 800;
  font-family: 'Roboto', 'Microsoft YaHei', sans-serif;
  letter-spacing: -0.6px;
  flex-shrink: 0;
  white-space: nowrap;
}

.value-unit-new {
  color: rgba(255, 255, 255, 0.65);
  font-size: 10px;
  font-weight: 500;
  margin-left: 2px;
  transform: translateY(-2px);
  flex-shrink: 0;
  white-space: nowrap;
}

.value-change-new {
  font-size: 11px;
  font-weight: 700;
  padding: 4px 10px;
  border-radius: 12px;
  position: relative;
  border: 1px solid rgba(255,255,255,0.22);
  background: linear-gradient(180deg, rgba(255,255,255,0.18), rgba(255,255,255,0.12));
  box-shadow: 0 2px 6px rgba(0,0,0,0.15);
  color: #ffffff;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  white-space: nowrap;
  backdrop-filter: blur(4px);
  margin-left:12px;
}

.value-change-new.change-up {
  background: linear-gradient(135deg, #ff6b6b 0%, #ff8a80 100%);
  border-color: rgba(255, 107, 107, 0.5);
  color: #ffffff;
}

.value-change-new.change-down {
  background: linear-gradient(135deg, #00d4aa 0%, #4ecdc4 100%);
  border-color: rgba(0, 212, 170, 0.5);
  color: #ffffff;
}

.value-change-new:hover { transform: translateY(-1px); }

.change-type {
  font-size: 10px;
  opacity: 0.9;
  margin-right: 3px;
  font-weight: 400;
  letter-spacing: 0.3px;
}


/* 不同指标类型的特殊样式 - 采用左侧边框风格 */
.capital-indicator {
  border-left-color: #29d9d5;
}

.risk-indicator {
  border-left-color: #ff6b6b;
}

.provision-indicator {
  border-left-color: #00d4aa;
}

.profit-indicator {
  border-left-color: #ffc107;
}

.efficiency-indicator {
  border-left-color: #9c27b0;
}

.liquidity-indicator {
  border-left-color: #2196f3;
}

/* 标题内容容器 */
.tit-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  position: relative;
}

.tit-main {
  font-size: 16px;
  font-weight: bold;
  color: #fff !important;
  flex: 1;
  font-family: Microsoft YaHei, 微软雅黑, PingFang SC, Helvetica Neue, Arial, sans-serif !important;
}

.group-name {
  font-size: 12px;
  color: white !important;
  font-weight: 500;
  background: rgba(255, 107, 107, 0.1);
  padding: 2px 8px;
  border-radius: 10px;
  border: 1px solid rgba(255, 107, 107, 0.3);
  transition: all 0.3s ease;
  white-space: nowrap;
  font-family: Microsoft YaHei, 微软雅黑, PingFang SC, Helvetica Neue, Arial, sans-serif !important;
}

/* 组名切换动画 */
.group-name-fade-enter-active,
.group-name-fade-leave-active {
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

.group-name-fade-enter-from {
  opacity: 0;
  transform: translateX(20px) scale(0.8) rotateY(-15deg);
}

.group-name-fade-leave-to {
  opacity: 0;
  transform: translateX(-20px) scale(0.8) rotateY(15deg);
}

/* 优化后的翻页动画效果 - 更流畅，减少GPU负担 */
.group-fade-enter-active,
.group-fade-leave-active {
  transition: opacity 0.6s ease-out;
}

.group-fade-enter-active .indicators-grid,
.group-fade-leave-active .indicators-grid {
  transition: transform 0.6s ease-out;
  will-change: transform; /* 启用GPU加速 */
}

.group-fade-enter-from .indicators-grid {
  transform: translateX(100%) rotateY(15deg);
  opacity: 0;
}

.group-fade-leave-to .indicators-grid {
  transform: translateX(-100%) rotateY(-15deg);
  opacity: 0;
}

/* 简化卡片动画，避免过多的3D变换 */
.group-fade-enter-active .indicator-card,
.group-fade-leave-active .indicator-card {
  transition: all 0.6s ease-out;
  will-change: transform, opacity; /* 启用GPU加速 */
}

.group-fade-enter-from .indicator-card {
  transform: translateX(50px) scale(0.9);
  opacity: 0;
}

.group-fade-leave-to .indicator-card {
  transform: translateX(-50px) scale(0.9);
  opacity: 0;
}

/* 减少延迟，让动画更连贯 */
.group-fade-enter-active .indicator-card:nth-child(1) {
  transition-delay: 0.05s;
}
.group-fade-enter-active .indicator-card:nth-child(2) {
  transition-delay: 0.1s;
}
.group-fade-enter-active .indicator-card:nth-child(3) {
  transition-delay: 0.15s;
}

/* 响应式调整和性能优化 */
@media (prefers-reduced-motion: reduce) {
  /* 为有运动敏感性或性能较低的设备简化动画 */
  .group-fade-enter-active,
  .group-fade-leave-active {
    transition: opacity 0.3s ease;
  }
  
  .group-fade-enter-active .indicators-grid,
  .group-fade-leave-active .indicators-grid {
    transition: opacity 0.3s ease;
  }
  
  .group-fade-enter-from .indicators-grid,
  .group-fade-leave-to .indicators-grid {
    transform: none;
    opacity: 0;
  }
  
  .group-fade-enter-active .indicator-card,
  .group-fade-leave-active .indicator-card {
    transition: opacity 0.3s ease;
    transition-delay: 0s;
  }
  
  .group-fade-enter-from .indicator-card,
  .group-fade-leave-to .indicator-card {
    transform: none;
    opacity: 0;
  }
}

/* 滚动容器样式 */
.indicators-scroll-container {
  height: 100%;
  overflow: hidden;
}

.indicators-scroll-container::-webkit-scrollbar {
  width: 4px;
}

.indicators-scroll-container::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 2px;
}

.indicators-scroll-container::-webkit-scrollbar-thumb {
  background: rgba(41, 217, 213, 0.5);
  border-radius: 2px;
}

.indicators-scroll-container::-webkit-scrollbar-thumb:hover {
  background: rgba(41, 217, 213, 0.7);
}
</style>
